import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  DatePicker,
  message,
  Popconfirm,
  Card,
  Row,
  Col,
  Tag,
  Tooltip
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExportOutlined,
  SearchOutlined,
  ReloadOutlined,
  SwapOutlined
} from '@ant-design/icons';
import { ContractApi, ContractVO, ContractPageParams } from '../../../api/crm/contract';
import dayjs from 'dayjs';

const { Option } = Select;
const { RangePicker } = DatePicker;

const ContractManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [contracts, setContracts] = useState<ContractVO[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchParams, setSearchParams] = useState<ContractPageParams>({});
  const [modalVisible, setModalVisible] = useState(false);
  const [editingContract, setEditingContract] = useState<ContractVO | null>(null);
  const [form] = Form.useForm();

  // 合同状态选项
  const statusOptions = [
    { label: '草稿', value: 0, color: 'default' },
    { label: '审批中', value: 1, color: 'processing' },
    { label: '审批通过', value: 2, color: 'success' },
    { label: '审批拒绝', value: 3, color: 'error' },
    { label: '已完成', value: 4, color: 'success' },
    { label: '已取消', value: 5, color: 'default' }
  ];

  // 获取合同列表
  const fetchContracts = async () => {
    setLoading(true);
    try {
      const params = {
        pageNo: currentPage,
        pageSize,
        ...searchParams
      };
      const response = await ContractApi.getContractPage(params);
      setContracts(response.data.list || []);
      setTotal(response.data.total || 0);
    } catch (error) {
      message.error('获取合同列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchContracts();
  }, [currentPage, pageSize, searchParams]);

  // 搜索处理
  const handleSearch = (values: any) => {
    const params = { ...values };
    if (values.orderDate && values.orderDate.length === 2) {
      params.orderDateStart = values.orderDate[0].format('YYYY-MM-DD');
      params.orderDateEnd = values.orderDate[1].format('YYYY-MM-DD');
      delete params.orderDate;
    }
    setSearchParams(params);
    setCurrentPage(1);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({});
    setCurrentPage(1);
  };

  // 新增合同
  const handleAdd = () => {
    setEditingContract(null);
    setModalVisible(true);
    form.resetFields();
  };

  // 编辑合同
  const handleEdit = (record: ContractVO) => {
    setEditingContract(record);
    setModalVisible(true);
    const formData = {
      ...record,
      orderDate: record.orderDate ? dayjs(record.orderDate) : null,
      startTime: record.startTime ? dayjs(record.startTime) : null,
      endTime: record.endTime ? dayjs(record.endTime) : null
    };
    form.setFieldsValue(formData);
  };

  // 删除合同
  const handleDelete = async (id: number) => {
    try {
      await ContractApi.deleteContract(id);
      message.success('删除成功');
      fetchContracts();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 更新合同状态
  const handleUpdateStatus = async (id: number, status: number) => {
    try {
      // 通过更新合同来改变状态
      const contract = contracts.find(c => c.id === id);
      if (contract) {
        await ContractApi.updateContract({ ...contract, auditStatus: status });
        message.success('状态更新成功');
        fetchContracts();
      }
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  // 转移合同
  const handleTransfer = async (id: number, newOwnerUserId: number) => {
    try {
      await ContractApi.transferContract([id], newOwnerUserId);
      message.success('转移成功');
      fetchContracts();
    } catch (error) {
      message.error('转移失败');
    }
  };

  // 保存合同
  const handleSave = async (values: any) => {
    try {
      const data = {
        ...values,
        orderDate: values.orderDate ? values.orderDate.format('YYYY-MM-DD') : null,
        startTime: values.startTime ? values.startTime.format('YYYY-MM-DD') : null,
        endTime: values.endTime ? values.endTime.format('YYYY-MM-DD') : null
      };

      if (editingContract) {
        await ContractApi.updateContract({ ...editingContract, ...data });
        message.success('更新成功');
      } else {
        await ContractApi.createContract(data);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchContracts();
    } catch (error) {
      message.error('保存失败');
    }
  };

  // 导出合同
  const handleExport = async () => {
    try {
      await ContractApi.exportContract(searchParams);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  // 获取状态标签
  const getStatusTag = (status: number) => {
    const option = statusOptions.find(opt => opt.value === status);
    return option ? (
      <Tag color={option.color}>{option.label}</Tag>
    ) : <Tag>未知</Tag>;
  };

  // 表格列定义
  const columns = [
    {
      title: '合同名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      ellipsis: true
    },
    {
      title: '合同编号',
      dataIndex: 'no',
      key: 'no',
      width: 120,
      ellipsis: true
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 120,
      ellipsis: true
    },
    {
      title: '商机名称',
      dataIndex: 'businessName',
      key: 'businessName',
      width: 120,
      ellipsis: true
    },
    {
      title: '合同金额',
      dataIndex: 'price',
      key: 'price',
      width: 120,
      render: (price: number) => price ? `¥${price.toLocaleString()}` : '-'
    },
    {
      title: '折扣金额',
      dataIndex: 'discountPrice',
      key: 'discountPrice',
      width: 120,
      render: (price: number) => price ? `¥${price.toLocaleString()}` : '-'
    },
    {
      title: '合同状态',
      dataIndex: 'auditStatus',
      key: 'auditStatus',
      width: 100,
      render: (status: number) => getStatusTag(status)
    },
    {
      title: '负责人',
      dataIndex: 'ownerUserName',
      key: 'ownerUserName',
      width: 100,
      ellipsis: true
    },
    {
      title: '下单时间',
      dataIndex: 'orderDate',
      key: 'orderDate',
      width: 120,
      render: (time: string) => time ? new Date(time).toLocaleDateString() : '-'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
      render: (time: string) => time ? new Date(time).toLocaleDateString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right' as const,
      render: (record: ContractVO) => (
        <Space>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="更新状态">
            <Button
              type="link"
              size="small"
              icon={<SwapOutlined />}
              onClick={() => {
                Modal.confirm({
                  title: '更新合同状态',
                  content: (
                    <Select
                      style={{ width: '100%', marginTop: 16 }}
                      placeholder="请选择新状态"
                      onChange={(value) => {
                        Modal.destroyAll();
                        handleUpdateStatus(record.id!, value);
                      }}
                    >
                      {statusOptions.map(option => (
                        <Option key={option.value} value={option.value}>
                          {option.label}
                        </Option>
                      ))}
                    </Select>
                  ),
                  okButtonProps: { style: { display: 'none' } },
                  cancelText: '取消'
                });
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个合同吗？"
            onConfirm={() => handleDelete(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Form
              layout="inline"
              onFinish={handleSearch}
              style={{ marginBottom: '16px' }}
            >
              <Form.Item name="name">
                <Input placeholder="合同名称" />
              </Form.Item>
              <Form.Item name="no">
                <Input placeholder="合同编号" />
              </Form.Item>
              <Form.Item name="customerId">
                <Input placeholder="客户ID" />
              </Form.Item>
              <Form.Item name="auditStatus">
                <Select placeholder="合同状态" style={{ width: 120 }} allowClear>
                  {statusOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="orderDate">
                <RangePicker placeholder={['开始时间', '结束时间']} />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </Button>
                  <Button onClick={handleReset} icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Col>
          <Col span={24}>
            <Space style={{ marginBottom: '16px' }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                新增合同
              </Button>
              <Button icon={<ExportOutlined />} onClick={handleExport}>
                导出
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={contracts}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size || 10);
            }
          }}
        />
      </Card>

      {/* 新增/编辑合同弹窗 */}
      <Modal
        title={editingContract ? '编辑合同' : '新增合同'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={800}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="合同名称"
                rules={[{ required: true, message: '请输入合同名称' }]}
              >
                <Input placeholder="请输入合同名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="no"
                label="合同编号"
                rules={[{ required: true, message: '请输入合同编号' }]}
              >
                <Input placeholder="请输入合同编号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="customerId"
                label="客户ID"
                rules={[{ required: true, message: '请输入客户ID' }]}
              >
                <InputNumber placeholder="请输入客户ID" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="businessId" label="商机ID">
                <InputNumber placeholder="请输入商机ID" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="price" label="合同金额">
                <InputNumber
                  placeholder="请输入合同金额"
                  style={{ width: '100%' }}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value!.replace(/\¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="discountPrice" label="折扣金额">
                <InputNumber
                  placeholder="请输入折扣金额"
                  style={{ width: '100%' }}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value!.replace(/\¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="orderDate" label="下单时间">
                <DatePicker placeholder="请选择下单时间" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="auditStatus" label="合同状态">
                <Select placeholder="请选择合同状态">
                  {statusOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="startTime" label="开始时间">
                <DatePicker placeholder="请选择开始时间" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="endTime" label="结束时间">
                <DatePicker placeholder="请选择结束时间" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="remark" label="备注">
                <Input.TextArea rows={3} placeholder="请输入备注" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default ContractManagement;